package top.itpath.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Assert;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import top.itpath.admin.dto.TokenInfo;
import top.itpath.admin.entity.SysUser;
import top.itpath.admin.service.ILoginService;
import top.itpath.admin.service.IUserService;
import top.itpath.common.util.JwtUtil;
import top.itpath.common.util.PasswordUtil;
import top.itpath.config.ApplicationProperties;

import java.time.Duration;

/**
 * @author zhaomengru
 * create by  2023/10/10 - 16:59
 */
@Service
@RequiredArgsConstructor
public class LoginServiceImpl implements ILoginService {

    private final IUserService userService;
    private final ApplicationProperties applicationProperties;

    @Override
    public TokenInfo login(String username, String password) {
        SysUser byUsername = userService.findByUsername(username);
        Assert.notNull(byUsername, "用户名或密码错误");
        if (!PasswordUtil.verify(password, byUsername.getSalt(), byUsername.getPassword())) {
            throw new IllegalArgumentException("用户名或密码错误");
        }
        String token = JwtUtil.createToken(byUsername);
        String refreshToken = JwtUtil.createToken(byUsername, Duration.ofSeconds(applicationProperties.getTokenExpireTime() + 3600));
        return new TokenInfo(token, refreshToken);
    }

    @Override
    public TokenInfo refreshToken() {
        String token = JwtUtil.createToken(JwtUtil.getSubject());
        String refreshToken = JwtUtil.createToken(JwtUtil.getSubject(), Duration.ofSeconds(applicationProperties.getTokenExpireTime() + 3600));
        return new TokenInfo(token, refreshToken);
    }
}
